import { UserConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'path';
import fs from 'fs'

const pathResolve = (pathStr: string) => {
  return path.resolve(__dirname, pathStr);
};

export default ({ cmd, mode }) => {

  let proxy = {}

  console.info('[环境]:\t', mode)

  if (!fs.existsSync('.env.development')) {
    fs.copyFileSync('.env.development.sample', '.env.development')
    throw new Error('[Error] 生成环境[' + mode + ']对应的.env[文件]，请重新执行脚手架运行')
  }

  const CONFIG = loadEnv(mode, __dirname)
  console.info('[环境变量]:\t', CONFIG)

  if (!CONFIG || !CONFIG.VITE_BASE_URL) {
    throw new Error('[Error] 环境[' + mode + ']对应的.env不存在, 请检查环境变量[文件]')
  }

  if (!!CONFIG.VITE_MOCK_URL) {
    proxy = {
      '/baseplatform/v1/': {
        target: CONFIG.VITE_MOCK_URL,
        changeOrigin: true,
        // rewrite: (path) => path.replace(/^\/baseplatform/, '/baseplatform')
      },
      '/asset/v1/': {
        target: 'http://192.168.203.3/',
        changeOrigin: true,
        // rewrite: (path) => path.replace(/^\/asset/, '/asset')
      },
    }
    console.info('[代理设置]:\t', proxy)
  }

  /**
      * @type {import('vite').UserConfig}
      */
  const viteConfig: UserConfig = {
    server: {
      // port: 1202, //一般不需要指定
      proxy: proxy,
    },
    plugins: [vue(), vueJsx()],
    alias: {
      '@': pathResolve('./src'),
    }
  }
  return viteConfig
}
